/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * contasPagar.java
 *
 * Created on 24/08/2010, 10:00:51
 */
package view;

import DAO.ContaPagarDAO;
import DAO.FornecedorDAO;
import controller.ContaPagar;
import controller.Fornecedor;
import java.awt.Dimension;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Alcivando
 */
public class contasPagar extends javax.swing.JInternalFrame {

    private static final contasPagar contas;

    static {
        contas = new contasPagar();
    }

    public static contasPagar getInstancia() {
        return contas;
    }
    private ContaPagarDAO dao;
    private DefaultTableModel modelo;

    /** Creates new form contasPagar */
    public contasPagar() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        btnPagar = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        txtCliente = new javax.swing.JTextField();
        txtValor = new javax.swing.JTextField();
        txtTroco = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabConta = new javax.swing.JTable();
        txtPesquisa = new javax.swing.JTextField();
        filtro = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();

        setBackground(new java.awt.Color(255, 255, 255));
        setClosable(true);
        setIconifiable(true);
        setTitle("Contas a Pagar");
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "dados da Conta a Pagar", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel3.setText("Valor");

        btnPagar.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        btnPagar.setText("Pagar");
        btnPagar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnPagar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnPagar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPagarActionPerformed(evt);
            }
        });

        jLabel6.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel6.setText("Fornecedor");

        jLabel7.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel7.setText("Troco");

        txtCliente.setFont(new java.awt.Font("Tahoma", 0, 12));
        txtCliente.setEnabled(false);

        txtValor.setFont(new java.awt.Font("Tahoma", 1, 24));
        txtValor.setEnabled(false);

        txtTroco.setFont(new java.awt.Font("Tahoma", 1, 24));
        txtTroco.setEnabled(false);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel6)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtCliente, javax.swing.GroupLayout.PREFERRED_SIZE, 286, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtValor, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel3))
                                .addGap(10, 10, 10)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel7)
                                    .addComponent(txtTroco, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addGap(41, 41, 41)
                        .addComponent(btnPagar, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(236, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel7)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txtTroco)
                            .addComponent(txtValor, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(26, 26, 26)
                        .addComponent(btnPagar, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 150, 700, -1));

        tabConta.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tabConta.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tabContaMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tabConta);

        getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 42, 700, 102));

        txtPesquisa.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtPesquisaKeyReleased(evt);
            }
        });
        getContentPane().add(txtPesquisa, new org.netbeans.lib.awtextra.AbsoluteConstraints(267, 11, 282, -1));

        filtro.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Representante", "Codigo", "Empresa" }));
        getContentPane().add(filtro, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 11, -1, -1));

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel4.setText("Pesquisar Fornecedor  por ");
        getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 13, -1, -1));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnPagarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPagarActionPerformed
        try {

            Double valorParcela;

            ContaPagarDAO cdao = new ContaPagarDAO();

            FornecedorDAO fdao = new FornecedorDAO();

            int linha = tabConta.getSelectedRow();

            valorParcela = Double.parseDouble(tabConta.getValueAt(linha, 3).toString());

            Fornecedor f = fdao.retornaFornecedorPorCodigo(Integer.parseInt(tabConta.getValueAt(linha, 0).toString()));

            Double valorTroco = Double.parseDouble(txtValor.getText()) - valorParcela;

            if (valorTroco <= 0.0) {

                valorTroco = 0.0;
                fdao.descontaConta(Double.parseDouble(txtValor.getText()), f, tabConta.getValueAt(linha, 5).toString());
                cdao.pagarParcela(f.getCodFornecedor());

            } else{
                fdao.descontaConta(Double.parseDouble(tabConta.getValueAt(linha, 3).toString()), f, tabConta.getValueAt(linha, 5).toString());
                cdao.pagarParcela(f.getCodFornecedor());
            }

            if (valorTroco != null) {
                txtTroco.setText(Double.toString(valorTroco));
            } else {
                txtTroco.setText("Não existe troco!");
            }

            txtValor.setEnabled(false);

            txtPesquisaKeyReleased(null);

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Erro: " + ex.getMessage(), "Erro", 0);
        }
    }//GEN-LAST:event_btnPagarActionPerformed

    private void tabContaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabContaMouseClicked
        int linha = tabConta.getSelectedRow();
        if (tabConta.getValueAt(linha, 2).equals("0.0")) {

            JOptionPane.showMessageDialog(null, "Não existe dividas com o fornecedor selecionado.", "Aviso", 1);

        } else {

            txtCliente.setText(tabConta.getValueAt(linha, 1).toString());
            txtTroco.setText("");
            txtValor.setEnabled(true);
        }
}//GEN-LAST:event_tabContaMouseClicked

    private void txtPesquisaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPesquisaKeyReleased
        modelo.setNumRows(0);

        ArrayList<Fornecedor> listaFornecedor;

        try {
            FornecedorDAO fdao = new FornecedorDAO();
            if (!txtPesquisa.getText().isEmpty()) {
                if (filtro.getSelectedItem().toString().equals("Representante")) {
                    listaFornecedor = fdao.retornaFornecedorPorNome(txtPesquisa.getText().toUpperCase());
                } else if (filtro.getSelectedItem().toString().equals("Código")) {
                    listaFornecedor = fdao.retornaFornecedorPorCod(Integer.parseInt(txtPesquisa.getText().toUpperCase()));
                } else {
                    listaFornecedor = fdao.retornaFornecedorPorNomeEmpresa(txtPesquisa.getText().toUpperCase());
                }
                for (Fornecedor f : listaFornecedor) {
                    ContaPagarDAO cdao = new ContaPagarDAO();
                    ContaPagar conta = cdao.retornarContaPorCodFonecedor(f.getCodFornecedor());
                    modelo.addRow(new String[]{Integer.toString(f.getCodFornecedor()), f.getRepresentante(), Double.toString(f.getValorConta()), Double.toString(conta.getValorParcela()), Integer.toString(conta.getnParcela()), conta.getVencimento()});
                }
            }


        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Erro: " + ex.getMessage(), "Erro", 0);
        }


}//GEN-LAST:event_txtPesquisaKeyReleased

    private void formWindowOpened(java.awt.event.WindowEvent evt) {

        String[] colunas = new String[]{"", "", "", "", "", ""};
        String[][] dados = new String[][]{};

        modelo = new DefaultTableModel(dados, colunas);

        

        tabConta.setModel(modelo);
        tabConta.getTableHeader().getColumnModel().getColumn(0).setHeaderValue("Código");
        tabConta.getTableHeader().getColumnModel().getColumn(1).setHeaderValue("Nome");
        tabConta.getTableHeader().getColumnModel().getColumn(2).setHeaderValue("Valor Conta");
        tabConta.getTableHeader().getColumnModel().getColumn(3).setHeaderValue("Valor Parcela");
        tabConta.getTableHeader().getColumnModel().getColumn(4).setHeaderValue("Parcelas Faltando");
        tabConta.getTableHeader().getColumnModel().getColumn(5).setHeaderValue("Vencimento");


        tabConta.getColumnModel().getColumn(0).setPreferredWidth(25);
        tabConta.getColumnModel().getColumn(1).setPreferredWidth(250);
        tabConta.getColumnModel().getColumn(2).setPreferredWidth(30);

    }

    public void primeiraLeitura() {

        txtCliente.setText("");
        txtPesquisa.setText("");
        txtTroco.setText("");
        txtValor.setText("");

        formWindowOpened(null);
        setVisible(true);

    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnPagar;
    private javax.swing.JComboBox filtro;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tabConta;
    private javax.swing.JTextField txtCliente;
    private javax.swing.JTextField txtPesquisa;
    private javax.swing.JTextField txtTroco;
    private javax.swing.JTextField txtValor;
    // End of variables declaration//GEN-END:variables
}
